<template>
  <van-nav-bar
    right-text="帮助"
    left-arrow
    @click-left="onClickLeft"
    @click-right="onClickRight"
  />
  <div class="pass_box">
    <div class="yi">
      <h2>输入验证码</h2>
      <p>
        验证码已发送至
        <!-- <sapn>+86<span>{{ loginData.username }}</span></sapn> -->
        <span>{{ loginData.username }}</span>
      </p>
    </div>
    <van-cell @touchstart.stop="show = true">
      <!-- 数字键盘 -->
      <!-- <van-number-keyboard v-model="loginData.inputCheckCode" :show="show" theme="custom" close-button-text="完成"
				@blur="show = false" @input="onInput" @delete="onDelete" /> -->
      <van-cell-group inset>
        <van-field
          :show="isLoginByPassword"
          @keyup.enter="login()"
          class="van-field1"
          v-model="loginData.inputCheckCode"
          maxlength="6"
          center
          clearable
          label="邮箱验证码"
          label-width="78"
          :rules="[{ required: true, message: '请填写验证码' }]"
          placeholder="请输入验证码"
        >
          <template #button>
            <van-button
              class="van-button1"
              @click="sendEmail()"
              :disabled="disabled"
              size="normal"
              type="primary"
              round
            >
              {{ countdown }}
            </van-button>
          </template>
        </van-field>
        <!-- 密码登录 -->
        <!-- <van-field :show="isLoginByPassword" @keyup.enter="login()" class="van-field1" v-model="loginData.inputCheckCode" maxlength="6" center clearable label="密码"
					label-width="78" :rules="[{ required: true, message: '请填写密码' }]" placeholder="请输入密码">
				</van-field> -->
      </van-cell-group>
    </van-cell>

    <van-button
      class="login-btn"
      @click="login()"
      round
      block
      color="#ffd101"
      native-type="submit"
      style="margin-top: 20px"
    >
      <span style="color: black; font-weight: bold">登 录</span>
    </van-button>
  </div>
</template>
<script>
import { Toast } from "vant";
import qs from "qs";
import storage from "../utils/localstorage.js";
export default {
  data() {
    return {
      //是否用密码登录
      isLoginByPassword: false,
      //登录数据
      loginData: {
        username: "",
        inputCheckCode: "",
        checkCode: "",
      },
      countdown: 59,
      value: "",
      phone: "",
      disabled: true,
      judge: false,
      show: false,
    };
  },
  mounted() {
    this.getUsername();
    this.setCountdown();
  },
  methods: {
    getUsername() {
      this.loginData.username = this.$route.query.username;
      console.log("this.$route.query.username=" + this.$route.query.username);
      console.log("this.loginData.username=" + this.loginData.username);
    },
    setCountdown() {
      this.phone = this.$route.params.username;
      this.disabled = true;
      let interval = setInterval(() => {
        this.countdown--;
        if (this.countdown === 0) {
          this.countdown = "重新发送";
          this.disabled = false;
          this.judge = true;
          clearInterval(interval);
        }
      }, 1000);
    },
    onInput(value) {
      Toast(value);
    },
    login() {
      if (this.loginData.inputCheckCode == "") {
        Toast.fail("请输入验证码");
        return;
      }
      this.$axios
        .post(
          "/user/login/with/verification/code",
          qs.stringify(this.loginData)
        )
        .then((res) => {
          storage.save("userId", res.result.data.id);
          storage.save("token", res.result.data.token);
          Toast.success("登录成功");
          this.$router.push("/homepage");
          if (null != res.result.userId) {
            console.log("userId=" + res.result.userId);
            this.loginData.userId = res.result.userId;
            this.assetsAdd();
          }
        });
    },
    assetsAdd() {
		console.log("新用户赠送优惠券")
    //   storage.save("userId", res.result.data.id);
    //   storage.save("token", res.result.data.token);
      this.$axios.post("/assets/add", this.loginData).then((res) => {
        if (res.result.data) {
          console.log("新用户赠送优惠券成功");
        } else {
          console.log("新用户赠送优惠券失败");
        }
      });
    },
    sendEmail() {
      /**
				 * 点击后给输入的邮箱发送一封带有验证码的的邮件。
					要求：1一个自然日只能给一个邮箱地址发送10封邮件
					2.验证码有效期为15分钟
					3.点击发送后进行60秒倒计时， 此时按钮不可用。倒计时完后显示重新发送
				 */
      if (!this.loginData.username) {
        // alert("");
        //已经全局加载了element-plus
        this.$message({
          message: "请输入邮箱",
        });
        return;
      }
      var regEmail =
        /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (
        this.loginData.username != "" &&
        !regEmail.test(this.loginData.username)
      ) {
        this.$message({
          message: "邮箱格式不正确",
          type: "error",
        });
        // this.loginData.username = ''
      }
      this.countdown = 59;
      this.disabled = true;
      /**
       * 定时器
       */
      let interval = setInterval(() => {
        this.countdown--;
        if (this.countdown === 0) {
          this.countdown = "重新发送";
          this.disabled = false;
          this.judge = true;
          clearInterval(interval);
        }
      }, 1000);
      // let data = qs.stringify(this.loginData)
      console.log("this.loginData.username=" + this.loginData.username);
      this.loginData.inputCheckCode = null;
      this.$axios
        .get("/user/mail/send", {
          params: {
            email: this.loginData.username,
          },
        })
        .then((res) => {
          this.loginData.checkCode = res.result.checkCode;
          console.log("checkCode=" + this.loginData.checkCode);
        })
        .catch((error) => {
          console.log(error);
        });
      this.$router.replace({
        path: "/verify",
        query: {
          username: this.loginData.username,
        },
      });
    },
    onClickLeft() {
      history.back();
    },
    onClickRight() {
      Toast.success("帮助");
    },
  },
  computed: {
    // if(this.countdown==0){
    // 	console.log(132);
    // }
  },
};
</script>
<style scoped>
* {
  font-family: "microsoft yahei";
}
.van-field1 {
  /* margin-left: -16px; */
}
.van-button1 {
  margin-left: -30px;
  /* margin-left: -20px; */
}
.pass_box {
  /* border: 1px solid red; */
  margin: 30px 20px 0px 20px;
}

.yi {
  margin-left: 16px;
}
.login-btn {
  font-size: 0.9em;
}
</style>
